const {
  GiftShopModel
} = require('../../../../utils/giftshop-model.js');
var giftShopModel = new GiftShopModel();
import {
  Config
} from '../../../../utils/config.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: null, //页面信息
    switchChecked: true, //默认与取件地址保持一致
    applyQuantity: 1, //申请数量
    tempFilePaths: [], //上传的图片
    problemDesc: '', //问题说明
    pickware: null, //取件地址
    returnware: null, //收货地址
    disabled: true,
    imgDisabled: false, //图片按钮
    isReason: false,
    title: '请选择申请原因',
    reason: '', //申请原因
    serviceType: '', //售后类型
    refundPrice: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const currency = JSON.parse(decodeURIComponent(options.currency))
    console.log(currency)
    let goodsPrice = currency.orderDetail.goodsPrice || 0
    let refundShippingFee = currency.refundShippingFee || 0
    let refundPrice = goodsPrice - refundShippingFee
    this.setData({
      detail: currency || null,
      applyQuantity: currency.orderDetail.goodsQty || 1, //申请数量
      pickware: currency.orderShipping || null, //取件地址
      returnware: currency.orderShipping || null, //收货地址
      serviceType: options.serviceType, //售后类型
      refundPrice: refundPrice > 0 ? refundPrice : 0,
    })
    wx.setNavigationBarTitle({
      title: options.serviceType == "20" ? "申请换货" : options.serviceType == "10" ? "申请退货" : ""
    })
  },

  /**
   * 是否与取件地址保持一致
   */
  switchChange(e) {
    var value = e.detail.value;
    this.setData({
      switchChecked: value
    })
  },

  /**
   * 减商品数量
   */
  decrease: function () {
    let quantity = parseInt(this.data.applyQuantity) - 1; //可申请的数量
    if (quantity > 0) {
      this.setData({
        applyQuantity: quantity
      })
    }
  },

  /**
   * 加商品数量
   */
  increase: function (e) {
    let num = e.currentTarget.dataset.num //可申请的数量
    let quantity = parseInt(this.data.applyQuantity) + 1; //单个商品数量
    if (num >= quantity) {
      this.setData({
        applyQuantity: quantity
      })
    }
  },

  /**
   * 上传图片
   */
  uploadPictures: function () {
    let that = this
    if (!that.data.imgDisabled) {
      wx.reportAnalytics('exchangegoods_uploadpictures');
      wx.chooseImage({
        count: 3 - that.data.tempFilePaths.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          var imgSize = res.tempFiles[0].size;
          if (imgSize < 5242880) {
            that.setData({
              imgDisabled: true
            })
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            res.tempFilePaths.forEach(element => {
              wx.uploadFile({
                url: Config.restUrl + '/wechat/mall/applet/user/upload/image', //仅为示例，非真实的接口地址
                filePath: element,
                name: 'file',
                formData: {
                  merchantId: wx.getStorageSync('merchantId') //商户ID
                },
                header: {
                  'content-type': 'multipart/form-data',
                  'token': wx.getStorageSync('token')
                },
                success(res) {
                  let data = JSON.parse(res.data)
                  if (res.statusCode == 200 && data.status == 200) {
                    let tempFilePaths = that.data.tempFilePaths.concat(data.data)
                    that.setData({
                      tempFilePaths: tempFilePaths,
                      imgDisabled: false
                    }, () => {
                      that.checkInfo()
                    })
                  } else if (res.statusCode == 200 && data.status == 400) {
                    wx.showToast({
                      title: `${data.error}`,
                      icon: 'none',
                      duration: 2000
                    })
                    that.setData({
                      imgDisabled: false
                    })
                  } else {
                    that.setData({
                      imgDisabled: false
                    })
                  }
                }
              })
            })
          } else {
            wx.showToast({
              title: '上传图片小于5M',
              icon: 'none',
              duration: 3000
            })
          }
        }
      })
    }
  },

  /**
   * 删除图片
   */
  delPictures: function (e) {
    wx.reportAnalytics('exchangegoods_deletepictures');
    let index = e.currentTarget.dataset.index //可申请的数量
    this.data.tempFilePaths.splice(index, 1);
    this.setData({
      tempFilePaths: this.data.tempFilePaths
    }, () => {
      this.checkInfo()
    })
  },

  /**
   * 换货原因
   */
  getReason: function (e) {
    console.log(e.detail)
    this.setData({
      reason: e.detail,
      isReason: false,
    }, () => {
      this.checkInfo()
    })
  },
  /**
   * 问题说明
   */
  setReasonValue: function (event) {
    var value = event.detail.value
    this.setData({
      problemDesc: value
    })
  },

  /**
   * 取件地址
   */
  setPickware: function (e) {
    wx.reportAnalytics('exchangegoods_pickwareaddress');
    wx.navigateTo({
      url: `/pages/giftShop/serviceOrder/address/index?address=${encodeURIComponent(JSON.stringify(this.data.pickware))}&type=1`
    })
  },

  /**
   * 收货地址
   */
  setReturnware: function (e) {
    wx.reportAnalytics('exchangegoods_returnwareaddress');
    wx.navigateTo({
      url: `/pages/giftShop/serviceOrder/address/index?address=${encodeURIComponent(JSON.stringify(this.data.returnware))}&type=2`
    })
  },

  /**
   * 选择原因
   */
  reasonShow: function () {
    this.setData({
      isReason: !this.data.isReason
    })
  },
  /**
   * 申请售后
   */
  submitService: function () {
    wx.reportAnalytics('exchangegoods_submit');
    let that = this.data;
    let pickwareAddress = {
      provinceCode: that.pickware.provinceCode,
      cityCode: that.pickware.cityCode,
      districtCode: that.pickware.areaCode,
      streetCode: that.pickware.streetCode,
      fullAddress: that.pickware.receiverAddress,
    }
    var param = {
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      orderCode: that.detail.orderCode, //订单号
      partnerSign: that.detail.partnerSign, //第三方id
      skuId: that.detail.orderDetail.goodsSku,
      quantity: 1, //申请数量
      // quantity: that.applyQuantity,
      serviceType: that.serviceType, //售后类型10.退货 20:换货
      problemDesc: that.problemDesc, //问题说明
      reason: that.reason, //退换货原因
      material: that.tempFilePaths, //上传图片
      priceType: that.detail.priceType,
    }
    param.pickware = pickwareAddress; //取件信息
    if (that.switchChecked) { //是否与订单收货地址一致
      param.returnware = pickwareAddress; //收件信息
    } else {
      param.returnware = {
        provinceCode: that.returnware.provinceCode,
        cityCode: that.returnware.cityCode,
        districtCode: that.returnware.areaCode,
        streetCode: that.returnware.streetCode,
        fullAddress: that.returnware.receiverAddress,
      }
    }
    param.customer = {
      contactName: that.pickware.receiver,
      phone: that.pickware.receiverPhone
    }
    giftShopModel.serviceOrderSave(param).then(data => {
      wx.redirectTo({
        url: `/pages/giftShop/serviceOrder/applySucceed/index?currency=${JSON.stringify(data)}`
      })
      console.log(JSON.stringify(data))
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 验证输入的内容
   */
  checkInfo: function () {
    var that = this;
    if (that.data.reason != '') {
      that.setData({
        disabled: false,
      })
    } else {
      that.setData({
        disabled: true,
      })
    }
  },
})